package com.lykj.llw.box.ui.activity

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.CountDownTimer
import com.blankj.utilcode.util.SPUtils
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.lykj.lib_base.base.BaseActivity
import com.lykj.lib_base.constants.BConstants
import com.lykj.lib_base.internal.inter.DiaFrgOnClickListener
import com.lykj.lib_base.internal.utils.ToastUtils
import com.lykj.lib_base.internal.utils.oaidHelper
import com.lykj.lib_base.net.http.CustomResponseBodyObserver
import com.lykj.lib_base.net.http.RetrofitManager
import com.lykj.llw.box.databinding.ActSplashBinding
import com.lykj.llw.box.ui.diafrg.AuthorizationDiaFrg
import io.reactivex.disposables.Disposable
import okhttp3.ResponseBody
import kotlin.system.exitProcess

/**
 * ================================================
 * 开屏页面
 * ================================================
 *
 * @author gosha
 * @date 2023/5/24-16:40
 */
class SplashActivity : BaseActivity() {
    lateinit var binding: ActSplashBinding

    private var mCountDownTimer: CountDownTimer? = null


    //默认授权登录为false
    private var mAuthLogin = false
    private var mBack = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 避免从桌面启动程序后，会重新实例化入口类的activity
        if (!this.isTaskRoot) {
            val intent = intent
            if (intent != null) {
                val action = intent.action
                if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN == action) {
                    finish()
                    return
                }
            }
        }

        val data: Uri? = intent?.data
        if (null != data && data.getQueryParameter("type") == "1") {
            mAuthLogin = true
            if (null != data!!.getQueryParameter("back")) {
                mBack = data!!.getQueryParameter("back").toString()
            }
        }

        binding = ActSplashBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initUI()
        initData()
        setListener()
    }

    override fun initUI() {
        ImmersionBar.with(this)
            .transparentBar()
            .statusBarDarkFont(true) //状态栏字体是深色，不写默认为亮色
            .navigationBarDarkIcon(true)
            .hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR)
            .navigationBarEnable(false)
            .init()

        val isGrant = SPUtils.getInstance().getBoolean("isGrant", false)

        if (isGrant) {
            BConstants.DEVICE_ID = oaidHelper.getOaid()
            if (mAuthLogin) {
                val intent = Intent(this@SplashActivity, HomeActivity::class.java)
                intent.putExtra("authLogin", true)
                intent.putExtra("back", mBack)
                startActivity(intent)
                finish()
            } else {
                startCountDown()
            }
            return
        }
        //判断是否同意隐协议,是倒计时进入主页,否弹出隐私弹窗
        AuthorizationDiaFrg()
            .setDiaFrgOnClickListener(object : DiaFrgOnClickListener {
                override fun sure(param: Any) {
                    SPUtils.getInstance().put("isGrant", true, true)
                    //开始倒计时准备进入主页
                    BConstants.DEVICE_ID = oaidHelper.getOaid()

                    startActivity(Intent(this@SplashActivity, HomeActivity::class.java))
                    finish()
                }

                override fun cancel() {
                    finish()
                    exitProcess(0)
                }
            })
            .show(supportFragmentManager, "")
    }

    private fun startCountDown() {
        mCountDownTimer = object : CountDownTimer(2000, 1000) {
            override fun onTick(p0: Long) {
            }

            override fun onFinish() {
                startActivity(Intent(this@SplashActivity, HomeActivity::class.java))
                finish()
            }
        }.start()
    }

    //获取首页Banner
    private fun obtainHomeBanner() {
        RetrofitManager.instance.obtainHomeBanner(object :
            CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@SplashActivity, d)
            }

            override fun specificHandle(responseBody: String) {
                SPUtils.getInstance("api_cache").put("home_banner", responseBody,true)
//                CacheDiskUtils.getInstance("api_cache").put("home_banner",responseBody)
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let {
                    ToastUtils.showShort(this@SplashActivity, it)
                }
            }
        })
    }

    //获取首页数据
    private fun obtainHomeData() {
        RetrofitManager.instance.obtainHome(object : CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@SplashActivity, d)
            }

            override fun specificHandle(responseBody: String) {
                SPUtils.getInstance("api_cache").put("home_data", responseBody,true)
//                CacheDiskUtils.getInstance("api_cache").put("home_data",responseBody)
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let {
                    ToastUtils.showShort(this@SplashActivity, it)
                }
            }
        })
    }

    override fun initData() {
        obtainHomeData()
        obtainHomeBanner()
    }

    override fun setListener() {
    }

    override fun onDestroy() {
        mCountDownTimer?.cancel()
        removeDisposables(this)
        super.onDestroy()
    }
}